import axios from 'axios'

// 定义http request 拦截器，添加数据请求公用信息
axios.interceptors.request.use(
  config => {
    // const token = getCookie('名称');注意使用的时候需要引入cookie方法，推荐js-cookie
    //config.data = JSON.stringify(config.data);
    let token = localStorage.token;
    //let token = 'xxx';
    let appid = 'xxx';
    let appID = decodeURIComponent(appid);
    config.headers.token = token;
    //config.headers['Content-Type'] = 'application/x-www-form-urlencoded';

    if (config.method == 'get') {
      config.params.app_id = appID
      config.params.token = token
    }
    if (config.method == 'post') {
      config.data.token = token
      config.data.app_id = appID
    }

    return config;
  },
  error => {
    return Promise.reject(err);
  }
);

// 封装get方法
export function get(url, params={}) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params
    }).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err)
    })
  })
};

// 封装post方法
export function post(url, params={}){
  return new Promise((resolve, reject) => {
    axios.post(url, params).then(res => {
      resolve(res.data)
    }, err => {
      reject(err)
    })
  })
};

// 封装patch请求
export function patch(url ,data={}){
  return new Promise((resolve, reject) => {
    axios.patch(url, data).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err)
    })
  })
};

// 封装put请求
export function put(url, data={}){
  return new Promise((resolve, reject) => {
    axios.put(url, data).then(res => {
      resolve(res.data)
    }, err => {
      reject(err)
    })
  })
};

// 实现跨域
const downloadUrl = url => {
  let iframe = document.createElement('iframe')
  iframe.style.display = 'none'
  iframe.src = url
  iframe.onload = function() {
      document.body.removeChild(iframe)
  }
  document.body.appendChild(iframe)
}
